﻿namespace Models
{
    public class Pager
    {
        private const int DefaultPageSize = 5;
        private const int DefaultCurrentPage = 1;

        public int PageSize;
        public int StartIndex;
        public int EndIndex;
        public int CurrentPage;
        public int ModelCount;
        public int PagesCount;
        public string CurrentUrl;

        public Pager(int modelCount,string currentUrl, int? currentPage,int pageSize = DefaultPageSize)
        {

            PageSize = pageSize;
            if (currentPage == null)
                CurrentPage = DefaultCurrentPage;
            else
                CurrentPage = (int)currentPage;
            
            ModelCount = modelCount;
           
            if (modelCount < pageSize)
                PagesCount = 1;
            else
                if (modelCount % pageSize != 0)
                    PagesCount = modelCount / pageSize + 1;
                else
                    PagesCount = modelCount / pageSize;

            StartIndex = pageSize * (CurrentPage - 1) + 1;
            if (PagesCount == CurrentPage)
                EndIndex = modelCount;
            else
                EndIndex = PageSize * CurrentPage;

            CurrentUrl = currentUrl;

        }

        public string GenerateUrl(int pageIndex,string orderBy,int? categoryId, string titleSearch,string textSearch)
        {
            string url;
            if (orderBy == null)
            {
                url = CurrentUrl + "/?page=" + pageIndex;

            }
            else
            {
                url = CurrentUrl + "/?page=" + pageIndex + "&orderBy=" + orderBy;
                
            }
            if (categoryId != null)
            {
                url += "&categoryId=" + categoryId;
            }
            if (titleSearch != null || titleSearch== "")
            {
                url += "&titleSearch=" + titleSearch;
            }
            if(textSearch != null || textSearch == "")
            {
                url += "&textSearch="+textSearch;
            }
            
            

            url = url.Replace("//", "/");
            return url;
        }

        public Pager Check()
        {
            if (CurrentPage > PagesCount || CurrentPage < 1)
                return null;
            return this;
        }
    }
}